﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SourceGrid;
using Aulac.Rsc.Bss.Tags;
using Aulac.Global.Common;
using Aulac.Rsc.Bss;
using Aulac.Rsc.Bss.Tags;
using Aulac.Client.Data.Bss.Helper.DataItems;

namespace Aulac.Client.Controls.Bss
{
    [System.ComponentModel.ToolboxItem(true)]
    public partial class GridBssBuyItem : Aulac.Client.Controls.UserControls.GridEditorCtrl
    {
        
        private Aulac.UtilityTools.DataGridEditors.CellEditors.ComboBox cbItemEditor = null;
        private Aulac.UtilityTools.DataGridEditors.CellEditors.ComboBox cbMdnGrpEditor = null;
        object mItemGrpID = "";
        public GridBssBuyItem()
        {
            InitializeComponent();
            grdData.DataSource = new Aulac.Client.Data.Bss.DataSet.DsGridBss.VchLineBuyItemDataTable();
            InitColumnShow();
            SetStyleOverInstock(Color.Chocolate);
        }

        #region Properties
        private InfoGrid.GridBuyItem _ColumnsGrd = new InfoGrid.GridBuyItem();
        public InfoGrid.GridBuyItem ColumnsGrd
        {
            get { return _ColumnsGrd; }
        }
        private List<ItemGrpTypes> mListMdnGrpTypes = null;
        public List<ItemGrpTypes> LstMdnGrpTypes
        {
            set {
                if (!Aulac.Global.Common.ValueHelper.EqualsValue(mListMdnGrpTypes, value))
                {
                    mListMdnGrpTypes = value;
                    ReLoadDataToControl();
                }
            }
        }
        double mTaxRate = 0;
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public double TaxRate
        {
            set
            {
                if (mTaxRate == value)
                    return;
                mTaxRate = value;
                SetValueInColumn(ColumnsGrd.VAT, mTaxRate);
                CalcAllRowsAmtItemLine(ColumnsGrd.VAT);
            }
        }
        #endregion 

        #region OverrideMethod
        protected override void OnFormLoad()
        {
            base.OnFormLoad();            
            ReLoadDataToControl();
        }
        public override void LoadDataToControl()
        {
            
            if(ValueHelper.isEmpty(mListMdnGrpTypes))
                return;
            if (cbMdnGrpEditor.Control.IsEmptyDataInList)
            {

                DataTable tbGrp = cbMdnGrpEditor.Control.GetTable();
                DataMdnItemsHelper.LoadMdnGroup(ref tbGrp, true, mListMdnGrpTypes.ToArray());
                cbMdnGrpEditor.Control.DataSource = tbGrp.DefaultView;
            }
             
            if (cbItemEditor.Control.IsEmptyDataInList )
            {
                string[] ArrFieldResult = new string[] {
                    tagItems.Items.ItemPrkID,
                    tagItems.Items.ItemID,
                    tagItems.Items.ItemName,
                    tagItems.Items.Unit,
                    
                    };
                DataTable tbItem = cbItemEditor.Control.GetTable();
               Aulac.Client.Data.Bss.Helper.DataItems.DataMdnItemsHelper.LoadMdnItem(ref tbItem, true, ArrFieldResult, mListMdnGrpTypes.ToArray());

                cbItemEditor.Control.DataSource = tbItem.DefaultView;                
            }
        }
        public override void ReLoadDataToControl()
        {
            cbMdnGrpEditor.Control.ClearDataContainer();
            cbItemEditor.Control.ClearDataContainer();
            LoadDataToControl();
        }
        protected override void OnClearValueControls()
        {
            base.OnClearValueControls();
            this.grdData.ClearDataContainer();
            this.txtTT.ClearValueControls();
        }

        protected override void OnCellEditorStarting(Aulac.UtilityTools.DataGridEditors.CellEditors.AulacEditorControl sender, CancelEventArgs e)
        {
            if (grdData.ReadOnly)
                return;
            if (Aulac.Global.Common.ValueHelper.EqualsValue(sender.Control, cbItemEditor))
            {
                string sGrpID = grdData.GetValueStringDataCell(sender.EditCellContext.Position.Row, ColumnsGrd.ItemGrpID);
                if (!Aulac.Global.Common.ValueHelper.isEmpty(sGrpID))
                {
                    DataView view = ((DataView)cbItemEditor.Control.DataSource);
                    view.RowFilter = string.Format("{0} = '{1}'", ColumnsGrd.ItemGrpID, sGrpID);
                    cbItemEditor.Control.DataSource = view;
                }
                grdData.SetValueCell(sender.EditCellContext.Position.Row, ColumnsGrd.VAT, mTaxRate);
                CalcAmtItemLine(sender.EditCellContext.Position.Row, ColumnsGrd.VAT);
            }
            else if (Aulac.Global.Common.ValueHelper.EqualsValue(sender.EditCellContext.Cell.Editor, cbMdnGrpEditor))
            {
                mItemGrpID = grdData.GetValueDataCell(grdData.SelectedIndexGridRow, ColumnsGrd.ItemGrpID);
            }
        }
        protected override void OnCellEditorEndding(Aulac.UtilityTools.DataGridEditors.CellEditors.AulacEditorControl sender, Aulac.UtilityTools.DataGridEditors.CellEditors.CellEditorEnddingEventArgs e)
        {
            if (e.Cancel == true)
                return;
            if (Aulac.Global.Common.ValueHelper.EqualsValue(sender.EditCellContext.Cell.Editor, cbMdnGrpEditor))
            {
                if (cbMdnGrpEditor.Control.SelectedIndex >= 0)
                {
                    DataView view = ((DataView)cbItemEditor.Control.DataSource);
                    string s = cbMdnGrpEditor.Control.GetValueItem(cbMdnGrpEditor.Control.SelectedIndex, ColumnsGrd.ItemGrpID);
                    view.RowFilter = string.Format("{0} = '{1}'", ColumnsGrd.ItemGrpID, s);// e.NewValue);
                    //cbItemEditor.Control.DataSource = null;
                    cbItemEditor.Control.DataSource = view;
                    int pRow = sender.EditCellContext.Position.Row;
                    string sItemID = grdData.GetValueStringDataCell(sender.EditCellContext.Position.Row, tagItems.Items.ItemPrkID);
               
                    //string sFeeTypeID = grdData.GetValueStringDataCell(sender.EditCellContext.Position.Row, tagItems.Items.FeeTypeID);
                    if (cbItemEditor.Control.FindItem(sItemID, tagItems.Items.ItemPrkID) <= 0)
                    {
                        grdData.SetValueCell(pRow, tagItems.Items.ItemPrkID, null);
                        grdData.SetValueCell(pRow, ColumnsGrd.ItemName, null);
                        grdData.SetValueCell(pRow, ColumnsGrd.ItemGrpID, null);
                    }
                }
            }
            else if (Aulac.Global.Common.ValueHelper.EqualsValue(sender.EditCellContext.Cell.Editor, cbItemEditor))
            {
                string sItemPrkID = cbItemEditor.Control.GetValueItem(tagItems.Items.ItemPrkID);
                //string sItemID = cbItemEditor.Control.GetValueItem(ColumnsGrd.ItemID);
                int pRows = checkItems(sItemPrkID);
                
                if (pRows != -1)
                {
                    Aulac.UtilityTools.MsgBox.Show(string.Format("Mặt hàng [{0}] đã tồn tại ở dòng {1}!", cbItemEditor.Control.GetValueItem(ColumnsGrd.ItemPrkID), pRows), "Warring", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    grdData.EndEditingRow(true);
                    e.Cancel = true;
                }
                else
                {
                    grdData.SetValueCell(grdData.SelectedIndexGridRow, tagItems.Items.ItemPrkID, sItemPrkID);
                    grdData.SetValueCell(grdData.SelectedIndexGridRow, ColumnsGrd.ItemName, cbItemEditor.Control.GetValueItem(ColumnsGrd.ItemName));
                    grdData.SetValueCell(grdData.SelectedIndexGridRow, ColumnsGrd.Unit, cbItemEditor.Control.GetValueItem(ColumnsGrd.Unit));
                    string s = cbItemEditor.Control.GetValueItem(ColumnsGrd.ItemGrpName);
                    grdData.SetValueCell(grdData.SelectedIndexGridRow, ColumnsGrd.ItemGrpName, s);
                }
                //grdData.SetValueCell(grdData.SelectedIndexGridRow, tagVch.Inv.OverInstock, false);
            }
            grdData.AutoStretchColumnsToFitWidth = true;
        }
        protected override void OnCellEditorEnd(Aulac.UtilityTools.DataGridEditors.CellEditors.AulacEditorControl sender, EventArgs e)
        {
            string s = cbItemEditor.Control.GetValueItem(ColumnsGrd.ItemGrpName);
            grdData.SetValueCell(grdData.SelectedIndexGridRow, ColumnsGrd.ItemGrpName, s);

            CalcAmtItemLine(sender.EditCellContext.Position.Row, ColumnsGrd.VAT);
            string colName = grdData.Columns[sender.EditCellContext.Position.Column].PropertyName;
            if (colName.Equals(ColumnsGrd.Quantity) || colName.Equals(ColumnsGrd.UnitPrice) ||
                colName.Equals(ColumnsGrd.AmtLineInExc) || colName.Equals(ColumnsGrd.AmtTaxLineInExc) || colName.Equals(ColumnsGrd.VAT))
            {
                CalcAmtItemLine(sender.EditCellContext.Position.Row, colName);
            }

            CalcAllRowsAmtItemLine(colName);
            grdData.Refresh();
        }
        #endregion
       
        #region Private Method
        private int checkItems(string pItemPrkID)
        {
            for (int i = 1; i < grdData.Rows.Count - 2; i++)
            {
                object obj = grdData.GetValueDataCell(i, tagItems.Items.ItemPrkID);
                string pValue = Convert.ToString(obj);
                if (ValueHelper.EqualsValue(pValue, pItemPrkID) && (i != grdData.SelectedIndexGridRow))
                    return i;
            }
            return -1;
        }

        private void InitColumnShow()
        {
            //grdData.AddColumnShow(tagItems.MdnGrpItems.ItemGrpPrkID, "", typeof(string));
            //grdData.AddColumnShow(tagItems.Items.ItemPrkID, "", typeof(string));
            
            grdData.ClearColumsShow();

            cbMdnGrpEditor = new Aulac.UtilityTools.DataGridEditors.CellEditors.ComboBox(typeof(string));

            cbMdnGrpEditor.Control.DisplayMember = ColumnsGrd.ItemGrpID;
            cbMdnGrpEditor.Control.ColumnNames = string.Format("{0}, {1}", tagItems.Items.ItemGrpID, tagItems.ItemGrps.ItemGrpName);
            cbMdnGrpEditor.Control.ValueMember = ColumnsGrd.ItemGrpID;
            cbMdnGrpEditor.Control.FieldMember = ColumnsGrd.ItemGrpID;
            cbMdnGrpEditor.Control.DataSource = new Aulac.Client.Data.Bss.DataSet.Catalog.Dm_MdnGrpItemsDataTable();
            cbMdnGrpEditor.Control.DropDownWidth = 270;
            cbMdnGrpEditor.Control.ColumnWidths = "70,200";
            DataGridColumn col = AddColumn(ColumnsGrd.ItemGrpID, "Nhóm mặt hàng", cbMdnGrpEditor);
            col.AutoSizeMode = SourceGrid.AutoSizeMode.EnableAutoSize;
            col.Width = 100;
            col.DataCell.Editor = cbMdnGrpEditor;
            

            cbItemEditor = new Aulac.UtilityTools.DataGridEditors.CellEditors.ComboBox(typeof(string));
            cbItemEditor.Control.DisplayMember = ColumnsGrd.ItemName;
            cbItemEditor.Control.ColumnNames = string.Format("{0}, {1}, {2}", tagItems.Items.ItemID, tagItems.Items.ItemName, tagItems.Items.Unit);
            cbItemEditor.Control.ValueMember = ColumnsGrd.ItemName;
            cbItemEditor.Control.FieldMember = tagItems.Items.ItemName;
            cbItemEditor.Control.DataSource = new Aulac.Client.Data.Bss.DataSet.Catalog.Dm_MdnItemsDataTable();
            cbItemEditor.Control.RemoveFieldMappingAll();
            cbItemEditor.Control.ListFieldMember = string.Format("{0}, {1}, {2}", tagItems.Items.ItemID, tagItems.Items.ItemName, tagItems.Items.Unit);
            cbItemEditor.Control.DropDownWidth = 300;
            cbItemEditor.Control.ColumnWidths = "70,200,30,80";
            cbItemEditor.Control.TabKey = Aulac.UtilityTools.KeysUse.EnterForTab;
            col = AddColumn(ColumnsGrd.ItemName, "Mặt hàng", cbItemEditor);
            col.AutoSizeMode = SourceGrid.AutoSizeMode.Default;
            col.Width = 150;

         

            col = AddColumn(ColumnsGrd.Unit, "ĐVT", typeof(string));
            col.Width = 80;
            col.DataCell.Editor.EnableEdit = false;
            col.AutoSizeMode = SourceGrid.AutoSizeMode.EnableAutoSize;

            SourceGrid.Cells.Editors.TextBoxNumeric numericEditor = new SourceGrid.Cells.Editors.TextBoxNumeric(typeof(double));
            numericEditor.TypeConverter = new DevAge.ComponentModel.Converter.NumberTypeConverter(typeof(double), "N");
            numericEditor.AllowNull = true;  //the database value can be null (System.DbNull)

            //col = AddColumn(ColumnsGrd.Quantity, "Số lượng", typeof(double));
            col = AddColumn(ColumnsGrd.Quantity, "Số lượng", typeof(double));
            col.Width = 80;
            col.AutoSizeMode = SourceGrid.AutoSizeMode.EnableAutoSizeView;

            col = AddColumn(ColumnsGrd.UnitPrice, "Đơn giá", typeof(double));
            col.Width = 160;
            col.AutoSizeMode = SourceGrid.AutoSizeMode.EnableAutoSizeView;

            col = AddColumn(ColumnsGrd.AmtLineInExc, "Thành tiền", typeof(double));
            col.Width = 180;
            col.AutoSizeMode = SourceGrid.AutoSizeMode.EnableAutoSizeView;

            col = AddColumn(ColumnsGrd.VAT, "VAT", numericEditor);
            col.Width = 80;
            col.AutoSizeMode = SourceGrid.AutoSizeMode.EnableAutoSizeView;

            col = AddColumn(ColumnsGrd.AmtTaxLineInExc, "Tiền thuế", typeof(double));
            col.Width = 160;
            col.AutoSizeMode = SourceGrid.AutoSizeMode.EnableAutoSizeView;

            col = AddColumn(ColumnsGrd.AmtLineInExc, "Tổng cộng", typeof(double));
            col.DataCell.Editor.EnableEdit = false;
            col.Width = 50;
            col.AutoSizeMode = SourceGrid.AutoSizeMode.EnableStretch;

            col = AddColumn(ColumnsGrd.NoteLine, "Ghi chú", typeof(string));
            col.Width = 150;
            col.AutoSizeMode = SourceGrid.AutoSizeMode.EnableAutoSize;

            /*col = AddColumn(tagVch.DrugPnt.ItemLine, "", typeof(int));
            col.Width = 0;
            col.AutoSizeMode = SourceGrid.AutoSizeMode.EnableAutoSize;
            */
            grdData.AutoStretchColumnsToFitWidth = true;
            grdData.ListFieldMember =
                StringHelper.ConvertArrayToString(", ", tagItems.Items.VchBuyItemPrkID, tagItems.Items.ItemPrkID, ColumnsGrd.NoteLine, ColumnsGrd.VAT, ColumnsGrd.UnitPrice, ColumnsGrd.Unit, ColumnsGrd.Specification, ColumnsGrd.Quantity, ColumnsGrd.AmtLineInExc, ColumnsGrd.AmtTaxLineInExc, tagVch.VchBuyLineItem.ItemLine);
        }
	    #endregion
        
        #region Public Method
        public void CalcAmtItemLine(int pRow, string pColName)
        {
            double dPrice = grdData.GetValueDoubleDataCell(pRow, ColumnsGrd.UnitPrice);
            double dQty = grdData.GetValueDoubleDataCell(pRow, ColumnsGrd.Quantity);
            double dAmtLine = grdData.GetValueDoubleDataCell(pRow, ColumnsGrd.AmtLineInExc);
            double dAmtTaxLineInExc = grdData.GetValueDoubleDataCell(pRow, ColumnsGrd.AmtTaxLineInExc);
            double dAmtTtlLineInExc = grdData.GetValueDoubleDataCell(pRow, ColumnsGrd.AmtLineInExc);
            double dTaxRate = grdData.GetValueDoubleDataCell(pRow, ColumnsGrd.VAT);

            if (pColName.Equals(ColumnsGrd.Quantity) || pColName.Equals(ColumnsGrd.UnitPrice))
            {
                dAmtLine = dPrice * dQty;
                dAmtTaxLineInExc = dAmtLine * dTaxRate / 100;
                dAmtTtlLineInExc = dAmtLine + dAmtTaxLineInExc;
                // Can tinh lai tong tien cho dAmtLineSvcInExc
                //dAmtLineSvcInExc = (dPriceSvc * dQty) + d 

            }
            else if (pColName.Equals(ColumnsGrd.AmtLineInExc))
            {
                dPrice = (dQty == 0) ? 0 : dAmtLine / dQty;
                dAmtTaxLineInExc = dAmtLine * dTaxRate / 100;
                dAmtTtlLineInExc = dAmtLine + dAmtTaxLineInExc;
            }
            else if (pColName.Equals(ColumnsGrd.AmtTaxLineInExc))
            {
                if (dAmtTaxLineInExc == 0)
                    dTaxRate = 0;
                dAmtTtlLineInExc = dAmtLine + dAmtTaxLineInExc;
            }
            else if (pColName.Equals(ColumnsGrd.VAT))
            {
                dAmtTaxLineInExc = dAmtLine * dTaxRate / 100;
                dAmtTtlLineInExc = dAmtLine + dAmtTaxLineInExc;
            }

            grdData.SetValueCell(pRow, ColumnsGrd.UnitPrice, dPrice);
            grdData.SetValueCell(pRow, ColumnsGrd.Quantity, dQty);
            grdData.SetValueCell(pRow, ColumnsGrd.AmtLineInExc, dAmtLine);
            grdData.SetValueCell(pRow, ColumnsGrd.AmtTaxLineInExc, dAmtTaxLineInExc);
            grdData.SetValueCell(pRow, ColumnsGrd.AmtLineInExc, dAmtTtlLineInExc);

            //grdData.SetValueCell(pRow, tagVch.Inv.PrimeCostInExc, (dQty == 0) ? 0 : dAmtTtlLineInExc / dQty);
            //grdData.SetValueCell(pRow, tagVch.Inv.AmtPrimeCostLineInExc, dAmtTtlLineInExc);
        }
        public void CalcAllRowsAmtItemLine(string pColName)
        {
            double mAllAmtItem = 0;
            int count = grdData.ReadOnly == true ? grdData.Rows.Count : grdData.Rows.Count - 1;
            for (int i = 1; i < count; i++)
            {
                CalcAmtItemLine(i, pColName);
                mAllAmtItem += (double)ValueHelper.ChangeType(grdData.GetValueDataCell(i, ColumnsGrd.AmtLineInExc), typeof(double));
            }
            txtTT.Double = mAllAmtItem;
        }
        public void SetStyleOverInstock(Color pForeColor)
        {
        //    SourceGrid.Cells.Views.Cell viewSelected = new SourceGrid.Cells.Views.Cell();
        //    viewSelected.Font = new Font(grdData.Font, FontStyle.Bold);
        //    viewSelected.ForeColor = pForeColor;
        //    //viewSelected.BackColor = Color.Chocolate;
        //    //Create selected conditions
        //    SourceGrid.Conditions.ConditionView selectedConditionBold = new SourceGrid.Conditions.ConditionView(viewSelected);
        //    selectedConditionBold.EvaluateFunction = delegate(SourceGrid.DataGridColumn column, int gridRow, object itemRow)
        //    {
        //        DataRowView row = (DataRowView)itemRow;
        //        if (row == null)
        //            return false;
        //        bool v = ValueHelper.ChangeBooleanType(Aulac.Global.Data.DataTableProcess.GetValue(row.Row, tagVch.Inv.OverInstock));
        //        //return row[tagVch.Inv.OverInstock] is bool &&  !ValueHelper.isEmpty(row[tagVch.Inv.OverInstock]) && (bool)row[tagVch.Inv.OverInstock] == true;
        //        return v;
        //    };

        //    foreach (SourceGrid.DataGridColumn col in grdData.Columns)
        //    {
        //        col.Conditions.Add(selectedConditionBold);
        //    }

        }
        public void CleareStyleOverInstock()
        {
            //foreach (SourceGrid.DataGridColumn col in grdData.Columns)
            //{
            //    col.Conditions.Clear();
            //}
        }

        #endregion
    }
}
